package mongo

import (
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
	"mongoDemo/parameter"
)

func (m *Mongo) QueryByCourseId(courseId string, user string) ([]parameter.ScoreParameter, error) {
	filter := bson.M{"$and": []bson.M{{"courseId": courseId}, {"user": user}}}
	opts := options.Find().SetSort(bson.D{{"dateTime", -1}})
	if courseId == "" && user != "" {
		filter = bson.M{"user": user}
	} else if courseId != "" && user == "" {
		filter = bson.M{"courseId": courseId}
	} else if courseId == "" && user == "" {
		filter = nil
	}
	result, err := m.db.Collection("blockchain").Find(context.TODO(), filter, opts)
	scores := make([]parameter.ScoreParameter, 0)
	for result.Next(context.TODO()) {
		var doc blockchainDoc
		innerErr := result.Decode(&doc)
		if innerErr == nil {
			scores = append(scores, parameter.ScoreParameter{
				CourseId:       doc.CourseId,
				MicroserviceId: doc.MicroserviceId,
				DateTime:       doc.DateTime,
				Scores:         doc.Scores,
				Comment:        doc.Comment,
				User:           doc.User,
				Hash:           doc.Hash,
			})
		}
	}
	return scores, err
}
